import { defineStore } from 'pinia';
import api from '@/axios.js'; // 你的axios实例
import router from '@/routers/index.js';
import axios from "axios";
import {ElMessage} from "element-plus";
import {useUserStore} from "@/stores/user.js";
import config from "@/config.js";


// 定义一个名为auth的store
export const useAuthStore = defineStore('auth', {
    state: () => ({
        token: localStorage.getItem('token') || null,
    }),

    actions: {
        // 登录
        async login(username, password) {
            // const { token } = await api.post('/login', { username, password });
            const response = await axios.post(config.apiBaseUrl+'/login', { username, password },{headers: {'Content-Type':'application/x-www-form-urlencoded'}});
            if (response.data.code !== 200) {
                console.log(response)
                ElMessage.error(response.data.msg);
            }
            const token = response.headers['authorization'];
            if (token){
                this.token = token;
                localStorage.setItem('token', token);
                console.log(token)
                router.push('/home');
            }

        },

        // 注销
        async logout() {
            this.token = null;
            localStorage.removeItem('token');
            router.push('/login');
        },

        // 刷新token
        // async refreshToken() {
        //     const { token } = await api.post('/refresh_token', { token: this.token });
        //     this.token = token;
        //     localStorage.setItem('token', token);
        //     return { token };
        // },

    }
});
